import { AfterViewInit, Component, OnInit } from '@angular/core';
import { WebGLService } from 'src/app/services/webgl.service';

@Component({
    selector: 'multi-point',
    templateUrl: './multi-point.component.html',
    styleUrls: ['./multi-point.component.scss']
})
export class MultiPointComponent implements OnInit, AfterViewInit {

    // 基本图元
    public baseGraph: string[] = ['POINTS', 'LINES', 'LINE_STRIP', 'LINE_LOOP', 'TRIANGLES', 'TRIANGLE_STRIP', 'TRIANGLE_FAN'];

    // 顶点着色器
    private vertexShaderSource = `
        attribute vec4 a_Position;
        void main () {
            gl_Position = a_Position;
            gl_PointSize = 10.0;
        }  
    `;
    private fragShaderSource = `
        void main () {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `;
    constructor(private webglService: WebGLService) { }
    ngOnInit() { }
    ngAfterViewInit () {
        this.init();
    }

    init (baseGraphType: string = 'POINTS') {
        const canvas = document.querySelector('#myCanvas') as HTMLCanvasElement;
        const gl = canvas.getContext('webgl');

        // 初始化 shader
        this.webglService.initShader(gl, this.vertexShaderSource, this.fragShaderSource);

        // 初始化 VertexBuffer
        const n = this.initVertexBuffer(gl);

        // 设置背景颜色
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        // 画点
        gl.drawArrays(gl[baseGraphType], 0, n);
    }

    private initVertexBuffer (gl: WebGLRenderingContext) {
        const vertices = new Float32Array([
            //x     y
           -0.5,    0.5,
            0.5,    0.5,
           -0.5,   -0.5,
            0.5,   -0.5
        ]);
        const n = 4;    // 点的个数
        const byteLen = vertices.BYTES_PER_ELEMENT;

        // 创建缓冲区对象
        const vertexBuffer = gl.createBuffer();
        
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const program = this.webglService.getProgramByGLContext(gl);
        const a_Position = gl.getAttribLocation(program, 'a_Position');

        // 将缓冲区对象分配给 a_Position 变量
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 2 * byteLen, 0);

        // 连接 a_Position 变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(a_Position);

        return n;
    }

    onSelectChange (event) {
        const baseGraphType = event.target.value;
        this.init(baseGraphType);
    }
}